package com.zrf.gulimall.order.web;

import com.zrf.gulimall.commnon.core.exception.CustomException;
import com.zrf.gulimall.commnon.core.utils.R;
import com.zrf.gulimall.common.database.utils.PageUtils;
import com.zrf.gulimall.order.service.OrderService;
import com.zrf.gulimall.order.vo.OrderConfirmVo;
import com.zrf.gulimall.order.vo.OrderSubmitVo;
import com.zrf.gulimall.order.vo.SubmitOrderResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author zhanrf
 * @Date 2022/1/6 21:19
 */
@Controller
@Slf4j
public class OrderWebController {
	@Autowired
	private OrderService orderService;

	@GetMapping("/toTrade")
	public String toTrade(Model model) {
		OrderConfirmVo orderConfirmVo = orderService.confirmOrder();
		model.addAttribute("confirmOrderData",orderConfirmVo);
		return "confirm";
	}

	@PostMapping("/submitOrder")
	public String submitOrder(OrderSubmitVo orderSubmitVo, Model model, RedirectAttributes attributes) {
		try {
			SubmitOrderResponseVo responseVo = orderService.submitOrder(orderSubmitVo);
			//下单成功来到支付选择页
			//下单失败回到订单确认页重新确定订单信息
			if (responseVo.getCode() == 0) {
				//成功
				model.addAttribute("submitOrderResp",responseVo);
				return "pay";
			} else {
				String msg = "下单失败";
				switch (responseVo.getCode()) {
					case 1: msg += "令牌订单信息过期，请刷新再次提交"; break;
					case 2: msg += "订单商品价格发生变化，请确认后再次提交"; break;
					case 3: msg += "库存锁定失败，商品库存不足"; break;
					default: break;
				}
				attributes.addFlashAttribute("msg",msg);
				return "redirect:http://order.gulimall.com/toTrade";
			}
		} catch (Exception e) {
			log.info(e.getMessage(), e);
			if (e instanceof CustomException) {
				String message = ((CustomException)e).getMsg();
				attributes.addFlashAttribute("msg",message);
			}
			return "redirect:http://order.gulimall.com/toTrade";
		}
	}

	@GetMapping("/memberOrder.html")
	public String memberOrder(@RequestParam(value = "pageNum",required = false,defaultValue = "0") Integer pageNum,
							  Model model, HttpServletRequest request) {
		//查出当前登录用户的所有订单列表数据
		Map<String,Object> params = new HashMap<>();
		params.put("page",pageNum.toString());
		//远程查询订单服务订单数据
		PageUtils page = orderService.queryPageWithItem(params);
		R orderInfo = R.ok().put("page", page);
		model.addAttribute("orders",orderInfo);
		return "orderList";
	}
}
